package primary.code10_BigData;

import lombok.extern.slf4j.Slf4j;

/**
 * 位图
 * <p>
 * 使用int数组来实现位图，要求提供以下两种操作
 * 1. 取位图上某一位的值
 * 2. 把位图上某一位置为0/1
 */
@Slf4j
public class Code02_BitMap {
    static class BitMap {
        private int size;
        private int[] arr;

        public BitMap(int n) {
            arr = new int[n / 32 + 1];
            size =n;
            log.info("size: {}, arr size:{}", size, arr.length);
        }

        public void put(int index, boolean v) {
            if (index < 0 || index >= size) {
                return;
            }
            int arrIndex = index / 32;
            int bitIndex = index % 32;
            int assignBit = 1 << bitIndex;
            if (v) {
                arr[arrIndex] |= assignBit;
            } else {
                arr[arrIndex] &= ~assignBit;
            }
        }

        public Boolean get(int index) {
            if (index < 0 || index >= size) {
                return null;
            }
            int arrIndex = index / 32;
            int bitIndex = index % 32;
            int arrInt = arr[arrIndex];
            return (arrInt & (1 << bitIndex)) == 0 ? false : true;
        }
    }

    public static void main(String[] args) {
        BitMap bitMap = new BitMap(100);
        bitMap.put(45, true);
        Boolean v1 = bitMap.get(45);
        log.info("v1: {}", v1);
        bitMap.put(45, false);
        Boolean v2 = bitMap.get(45);
        log.info("v2: {}", v2);
    }
}
